package com.sxkiler.demo.rpc.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcClient {
    private static ExecutorService executorService = Executors.newFixedThreadPool(8);//创建一个线程池
    RpcClientHandler rpcClientHandler;

    public RpcClient(String host,int port){
        rpcClientHandler = new RpcClientHandler();
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MessageDecoder());//自定义解码器
                            pipeline.addLast(new MessageEncoder());//自定义编码器
                            pipeline.addLast(rpcClientHandler);
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port).sync();
            if (future.isSuccess()){
                System.out.println("连接到服务端，开始调用服务");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
//            if(eventLoopGroup != null) {
//                eventLoopGroup.shutdownGracefully();
//            }
        }
    }


    public RpcClientHandler getRpcClientHandler() {
        return rpcClientHandler;
    }

    public static void main(String[] args) throws InterruptedException {
        // NacosTemplate nacosTemplate = new NacosTemplate();//集成nacos用，这里可以去掉
        RpcClientHandler nettyClientHandler = new RpcClientHandler();

    }
}

